// 导入@vue/compat用于兼容Vue 2代码
// @ts-ignore
import Vue from '@vue/compat'
// import SvgIcon from './vue2-flow/src/components/SvgIcon/index.vue'; // svg component
// Vue.component('svg-icon', SvgIcon);
import {createApp} from 'vue'
import App from './App.vue'
import router, {setupRouter} from '@/router'
import i18n from '@/i18n/index'
import {setupStore} from '@/store'
import {setupNaive, setupDirectives, setupCustomComponents} from '@/plugins'
import {GoAppProvider} from '@/components/GoAppProvider/index'
import {setHtmlTheme} from '@/utils'
import {addCollection} from 'iconify-icon'
import uimIcons from '@iconify/json/json/uim.json'
import lineMdIcons from '@iconify/json/json/line-md.json'
import wiIcons from '@iconify/json/json/wi.json'
import emojione from '@iconify/json/json/emojione.json' //backhand-index-pointing-up
import './vue2-flow/src/icons/index.js' // icon
// 引入全局样式
import '@/styles/pages/index.scss'
// 引入动画
import 'animate.css/animate.min.css'
// 引入标尺
import 'vue3-sketch-ruler/lib/style.css'
// 引入Mitt库
import mitt from 'mitt'
// 创建Mitt实例
const Emitter = mitt()

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

// 注册图标
addCollection(uimIcons)
addCollection(lineMdIcons)
addCollection(wiIcons)
addCollection(emojione)

// 处理less相关（以下只是示例，需根据实际情况完善less的正确使用，比如确保构建工具能处理less编译等）
// 如果原Vue 2项目中关于less的引入部分是有效的且想继续使用，按以下方式调整（假设路径等正确）
// const Less = require('../public/libs/less.js')
// Vue.use(Less)
// 改为如下导入（可能需要进一步配置项目构建工具来处理less文件，这里只是导入语句调整）
// @ts-ignore
// import Less from '../public/libs/less.js'
//
// Vue.use(Less as any)

// ElementUI相关（尝试兼容使用，后续最好迁移到Element Plus，需测试验证其兼容性）
// @ts-ignore
// import ELEMENT_UI from '../public/libs/elementui2.15.14/theme.js'
// const ELEMENT_UI = require('../public/libs/elementui2.15.14/theme.js')
// Vue.use(ELEMENT_UI, { size: 'mini' })
//
// Vue.use(ELEMENT_UI as any, {size: 'mini'})
// const ELEMENT_UI = require('../public/libs/elementui2.15.14/theme.js');
// lodash相关，暂时保持在原型上挂载的方式，后续可按需优化
const lodash = require('../public/libs/lodash.min-4.17.21.js')
// @ts-ignore
window['$lodash'] = lodash
//
// // httpVueLoader相关（需测试是否能在Vue 3环境下正常工作）
// const httpVueLoader = require('../public/libs/vue/VueLoader.js')
// Vue.use(httpVueLoader)

// form-create相关（示例，不确定能否完全兼容，需测试调整）

// 导入自定义指令相关代码
// @ts-ignore
// import Directive from './libs/Directive.js'

// 导入各种自定义组件
// @ts-ignore
import Contextmenu from '@/vue2-flow/src/libs/contextmenu.umd.js'
// 解构获取COMPONENT_NAME和Submenu
// const { COMPONENT_NAME, Submenu } = Contextmenu;
import NodeInputSourceDataComponent from './vue2-flow/src/views/flow/components/NodeInputSourceDataComponent.vue'
// @ts-ignore
// import Designer from './vue2-flow/src/views/UserPage/Temp/Designer/Index.vue'
// @ts-ignore
import LoginDialog from './vue2-flow/src/views/UserPage/LoginDialog.vue'
// @ts-ignore
import DataManage from './vue2-flow/src/views/dataManage/Index.vue'
// @ts-ignore
import GlobalParam from './vue2-flow/src/views/GlobalParam/Index.vue'
// @ts-ignore
import {Datasource} from "@/components/Datasource/index";

// @ts-ignore
import flow from './vue2-flow/src/views/flow/constants/index.js'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
// @ts-ignore
import store from './vue2-flow/src/store'
// @ts-ignore
import SvgIcon from "@/vue2-flow/src/components/SvgIcon/index.vue";
// @ts-ignore
import Utils from "@/vue2-flow/src/utils/Common.js";
// @ts-ignore
import AppInitialize from "@/api/flow/AppInitialize.js";

import {SocketClient} from "@/api/socket";

async function appInit() {
    const start = new Date().getTime()
    const goAppProvider = createApp(GoAppProvider)

    const app = createApp(App)

    app.component('data-source-input', NodeInputSourceDataComponent);

    // app.component(COMPONENT_NAME, Submenu);
    // 将FLOW挂载为全局属性，采用Vue 3推荐的方式（逐步替换原来Vue 2的原型挂载方式）
    app.use(ElementPlus)

    const Socket = new SocketClient('ws://127.0.0.1:9631/ws', 3000, 5);
    Socket.connect()
    Socket.onError = (data)=>{
        alert('连接失败：ws://127.0.0.1:9631/ws')
    }
    // Socket.onMessage = (data: string | ArrayBuffer) => {
    //     console.log("收到消息：" + data)
    // }
    app.config.globalProperties.FLOW = flow
    app.config.globalProperties.$emitter = Emitter
    app.config.globalProperties.$lodash = lodash
    app.config.globalProperties.$Socket = Socket

    // app.config.globalProperties.$vue2Component = Vue2Component;
    // app.use(CodeMirror)
    // 挂载状态管理
    setupStore(app)
    app.use(store)
    // elementUIScript.install(app, {size: 'mini'})
    // 注册全局常用的 naive-ui 组件
    setupNaive(app)
    // Vue.use(ELEMENT_UI, { size: 'mini' })
    // 注册全局自定义指令
    // 注册全局自定义指令
    setupDirectives(app)
    // Object.keys(Directive).forEach(key => {
    //     app.directive(key, Directive[key])
    // })
    // 示例：对单独定义的'permission'指令按照Vue 3规范调整（需完善实际逻辑）
    app.directive('permission', {
        beforeMount(el, binding, vnode) {
            if (Utils.IsAuthentication()) {
                const UserInfo = Utils.GetLoginUserInfo()
                if (UserInfo.role === '5') {
                    el.style.display = 'block';
                } else {
                    const UserPermissions = UserInfo.Permissions?.Data.map((p: any) => p.page + '::' + p.key);
                    if (UserPermissions?.includes(binding.value)) {
                        el.style.display = 'block';
                    } else {
                        el.style.display = 'none';
                    }
                }
            }
        },
        beforeUpdate(el, binding, vnode) {
            if (Utils.IsAuthentication()) {
                const UserInfo = Utils.GetLoginUserInfo()
                if (UserInfo.role === '5') {
                    el.style.display = 'block';
                } else {
                    const UserPermissions = UserInfo.Permissions?.Data.map((p: any) => p.page + '::' + p.key);
                    if (UserPermissions?.includes(binding.value)) {
                        el.style.display = 'block';
                    } else {
                        el.style.display = 'none';
                    }
                }
            }
        }
    })

    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
        app.component(key, component)
    }

    // 注册全局自定义组件
    setupCustomComponents(app)
    // 注册全局自定义组件
    app.component('svg-icon', SvgIcon)
    app.component('data-source', Datasource)
    // 解决路由守卫，Axios中可使用，Dialog，Message 等全局组件
    goAppProvider.mount('#appProvider', true)

    // 挂载路由
    setupRouter(app)

    // 路由准备就绪后挂载APP实例
    await router.isReady()
    console.log(new Date().getTime() - start)
    // Store 准备就绪后处理主题色
    setHtmlTheme()

    // 语言注册
    app.use(i18n)

    // 挂载到页面
    app.mount('#app', true)

    // 挂载到 window
    window['$vue'] = app

}

appInit().then(() => {
    const App = new AppInitialize()
    App.OnWindow()
        .OnInternalEvent()
        .LoadingNodeGroup()
        .LoadingAllFlow()
        .LoadingDevice()
        .LoadingSystemConfig()
        .LoadingGlobalConfig()
        .RegisterGlobalFunction()
        .MessageForward()
})
